package com.lyf.boot.config;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;

/**
 * @author Luyufan
 * @date 2023/7/10 16:36
 */
@Slf4j
public class MqttServer {

    private static MqttClient mqttClient;

    private MqttServer(){}

    public static void setMqttClient(MqttClient mqttClient){
        MqttServer.mqttClient = mqttClient;
    }

    public static void disconnect(){
        try {
            mqttClient.disconnect();
        } catch (MqttException e) {
            log.error("mqtt断开连接失败",e);
        }
    }

    public static void subscribe(String topic, int qos){
        try {
            mqttClient.subscribe(topic, qos);
        } catch (MqttException e) {
            log.error("mqtt订阅失败",e);
        }
    }

    public static void subscribe(String topic, IMqttMessageListener messageListener){
        try {
            mqttClient.subscribe(topic, messageListener);
        } catch (MqttException e) {
            log.error("mqtt订阅失败",e);
        }
    }



    public static void publish(int qos, boolean retained, String topic, String message){
        MqttMessage mqttMessage = new MqttMessage();
        mqttMessage.setQos(qos);
        mqttMessage.setRetained(retained);
        mqttMessage.setPayload(message.getBytes());
        //主题目的地，用于发布/订阅消息
        MqttTopic mqttTopic = mqttClient.getTopic(topic);
        //提供一种机制来跟踪消息的传递进度。
        //用于在以非阻塞方式（在后台运行）执行发布时跟踪消息的传递进度
        MqttDeliveryToken token;
        try {
            //将指定消息发布到主题，但不等待消息传递完成。返回的token可用于跟踪消息的传递状态。
            //一旦此方法干净地返回，消息就已被客户端接受发布。当连接可用时，将在后台完成消息传递。
            token = mqttTopic.publish(mqttMessage);
            token.waitForCompletion();
        } catch (MqttException e) {
            log.error("mqtt发布失败",e);
        }
    }
}
